using System;
using System.Collections.Generic;
using System.Reflection;
using System.Windows.Forms;
using EnvDTE;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.TestTools.Common;
using Microsoft.VisualStudio.TestTools.Exceptions;
using Microsoft.VisualStudio.TestTools.Vsip;
using NUnitForVSTS.NUnitTest.Properties;
using System.Globalization;

namespace NUnitForVSTS.NUnitTest
{
    /// <summary>
    /// Nunit Test User Interface Provider components
    /// Provides extensions to the test user interface
    /// </summary>
	class NUnitTestTuip:BaseTuip, ITestService
	{
		public static Dictionary<TestResultId, int> ResultWindowMapping = new Dictionary<TestResultId, int>();
		int idNext;

        /// <summary>
        /// Initializes a new instance of the <see cref="NUnitTestTuip"/> class.
        /// </summary>
        /// <param name="isp">The isp.</param>
		public NUnitTestTuip(IServiceProvider isp) : base(isp)
		{
		}

        /// <summary>
        /// Invokes the result viewer.
        /// </summary>
        /// <param name="resultMessage">The result message.</param>
		public override void InvokeResultViewer(TestResultMessage resultMessage)
		{
			NUnitTestPackage package = NUnitTestPackage.Instance;

			TestResult result = resultMessage as TestResult;
            if (result == null || result.Test == null)
            {
                throw new ArgumentException(Resources.InvalidTestResult);
            }

            if (result.Outcome == TestOutcome.Pending || result.Outcome == TestOutcome.InProgress)
            {
                VSMessageBoxShowError(package, Resources.ResultsForIncompleteTest);
            }
            else if (result.Outcome == TestOutcome.NotExecuted)
            {
                VSMessageBoxShowError(package, Resources.ResultsForNotExecutedTest);
            }
            else
            {
                int idWindow;
                if (!ResultWindowMapping.TryGetValue(result.Id, out idWindow))
                {
                    idWindow = idNext++;
                }

                ToolWindowPane window = package.FindToolWindow(typeof(NUnitTestResultViewWindow), idWindow, true);
                NUnitTestResultViewWindow windowResult = window as NUnitTestResultViewWindow;
                if (windowResult == null || windowResult.Frame == null)
                {
                    throw new EqtException(Resources.ResultWindowCouldNotBeCreated);
                }
                windowResult.LoadResult(result);

                ((IVsWindowFrame)windowResult.Frame).SetProperty((int)__VSFPROPID.VSFPROPID_Caption, string.Format(CultureInfo.CurrentUICulture,"{0} (Results)", result.Test.Name));
                ((IVsWindowFrame)windowResult.Frame).Show();

                if (!ResultWindowMapping.ContainsKey(result.Id))
                {
                    ResultWindowMapping.Add(result.Id, idWindow);
                }
            }

		}

        /// <summary>
        /// message box show error is visual studio.
        /// </summary>
        /// <param name="serviceProvider">The service provider.</param>
        /// <param name="text">The text.</param>
		private static void VSMessageBoxShowError(IServiceProvider serviceProvider, string text)
		{
            MessageBox.Show(text);
            /*
			Type type = Type.GetType("Microsoft.VisualStudio.TestTools.Vsip.VSMessageBox, Microsoft.VisualStudio.QualityTools.Vsip");
			MethodInfo method = type.GetMethod("ShowError", BindingFlags.Public | BindingFlags.Static, null,
			                                   new[] { typeof(IServiceProvider), typeof(string) }, null);
			method.Invoke(null, new object[] { serviceProvider, text });*/
		}

        /// <summary>
        /// Closes the result viewer.
        /// </summary>
        /// <param name="resultMessage">The result message.</param>
		public override void CloseResultViewer(TestResultMessage resultMessage)
		{
			TestResult result = resultMessage as TestResult;
			
			if(ResultWindowMapping.ContainsKey(result.Id))
			{
				int toolWindowId = ResultWindowMapping[result.Id];
				ToolWindowPane windowPane = NUnitTestPackage.Instance.FindToolWindow(typeof(NUnitTestResultViewWindow), toolWindowId, false);
				NUnitTestResultViewWindow resultWindow = windowPane as NUnitTestResultViewWindow;

                if (resultWindow != null)
                {
                    ((IVsWindowFrame)resultWindow.Frame).CloseFrame(0);
                }
			}
		}

        /// <summary>
        /// Gets the run configuration editor.
        /// </summary>
        /// <value>The run configuration editor.</value>
		public override IRunConfigurationCustomEditor RunConfigurationEditor
		{
			get { return null; }
		}

	}
}
